<template>
    <div class="merchant-approval-container">
        <div class="header-card">
            <h2>商家入驻审核</h2>
            <p>管理商家入驻申请，审核商家资质</p>
        </div>

        <el-card class="table-card" shadow="never">
            <el-table :data="tableData" style="width: 100%" border stripe v-loading="loading">
                <el-table-column prop="id" label="ID" width="80" align="center" />
                <el-table-column prop="shop_name" label="商家名称" min-width="180" />
                <el-table-column label="申请地区" min-width="200">
                    <template #default="scope">{{ getFullLocation(scope.row) }}</template>
                </el-table-column>
                <el-table-column prop="leader_name" label="负责人" width="120" align="center" />
                <el-table-column prop="create_time" label="申请时间" width="170" align="center">
                    <template #default="scope">{{ formatDate(scope.row.create_time) }}</template>
                </el-table-column>
                <el-table-column label="申请状态" width="120" align="center">
                    <template #default="scope">
                        <el-tag :type="getStatusType(scope.row.apply_status)" effect="dark">
                            {{ getStatusText(scope.row.apply_status) }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="160" fixed="right" align="center">
                    <template #default="scope">
                        <el-button size="small" type="primary" plain @click="viewDetail(scope.row)" round>
                            查看详情
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>

            <div class="pagination-container">
                <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
                    :page-sizes="[10, 20, 50, 100]" :total="total" layout="total, sizes, prev, pager, next, jumper"
                    @size-change="handleSizeChange" @current-change="handleCurrentChange" />
            </div>
        </el-card>

        <el-dialog v-model="dialogVisible" :title="detailDialogTitle" width="650px" :before-close="handleDialogClose">
            <el-form :model="detailData" label-width="100px" label-position="left">
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="商家名称:">
                            <span class="form-value">{{ detailData.shop_name }}</span>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="负责人:">
                            <span class="form-value">{{ detailData.leader_name }}</span>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="联系电话:">
                            <span class="form-value">{{ detailData.leader_phone }}</span>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="申请时间:">
                            <span class="form-value">{{ formatDate(detailData.create_time) }}</span>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-form-item label="所在地区:">
                    <span class="form-value">{{ getFullLocation(detailData) }}</span>
                </el-form-item>

                <el-form-item label="详细地址:">
                    <span class="form-value">{{ detailData.address }}</span>
                </el-form-item>

                <el-form-item label="身份证号:">
                    <span class="form-value">{{ detailData.leader_idcard }}</span>
                </el-form-item>

                <el-form-item label="商家账号:">
                    <span class="form-value">{{ detailData.accout }}</span>
                </el-form-item>

                <el-form-item label="申请状态:">
                    <el-tag :type="getStatusType(detailData.apply_status)" size="small">
                        {{ getStatusText(detailData.apply_status) }}
                    </el-tag>
                </el-form-item>

                <el-form-item label="营业执照:">
                    <div class="license-container">
                        <el-image v-if="getImageUrl(detailData.image_url)" :src="getImageUrl(detailData.image_url)"
                            class="license-image" :preview-src-list="[getImageUrl(detailData.image_url)]" fit="cover"
                            hide-on-click-modal>
                            <template #error>
                                <div class="image-slot">
                                    <i class="el-icon-picture-outline"></i>
                                    <span>图片加载失败</span>
                                </div>
                            </template>
                        </el-image>
                        <div v-else class="no-license">
                            <i class="el-icon-document"></i>
                            <span>暂无营业执照</span>
                        </div>
                    </div>
                </el-form-item>

                <el-form-item v-if="showRejectReason" label="拒绝原因:" required class="reject-reason">
                    <el-input v-model="rejectReason" type="textarea" placeholder="请输入拒绝原因" :rows="3" maxlength="200"
                        show-word-limit />
                </el-form-item>
            </el-form>

            <template #footer>
                <div class="dialog-footer">
                    <template v-if="detailData.apply_status === '0'">
                        <el-button @click="handleDialogClose" round>取消</el-button>
                        <el-button type="success" @click="approveApplication('1')" round>
                            通过申请
                        </el-button>
                        <el-dropdown v-if="!showRejectReason" trigger="click" @command="toggleRejectReason">
                            <el-button type="danger" round>
                                拒绝申请<i class="el-icon-arrow-down el-icon--right"></i>
                            </el-button>
                            <template #dropdown>
                                <el-dropdown-menu>
                                    <el-dropdown-item command="reason">填写拒绝原因</el-dropdown-item>
                                </el-dropdown-menu>
                            </template>
                        </el-dropdown>
                        <template v-else>
                            <el-button type="danger" @click="approveApplication('2')" :disabled="!rejectReason.trim()"
                                round>
                                确认拒绝
                            </el-button>
                            <el-button @click="cancelReject" round>返回</el-button>
                        </template>
                    </template>

                    <el-button v-if="detailData.apply_status !== '0'" @click="closeDialog" round>
                        关闭
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'

const tableData = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const loading = ref(false)
const dialogVisible = ref(false)
const detailData = ref({})
const showRejectReason = ref(false)
const rejectReason = ref('')
const baseUrl = 'http://localhost:8889' // 后端服务地址

const detailDialogTitle = computed(() => {
    if (!detailData.value.shop_name) return '商家申请详情'
    const statusMap = { '0': '待审批', '1': '已通过', '2': '已拒绝' }
    const statusText = statusMap[detailData.value.apply_status] || '未知状态'
    return `${detailData.value.shop_name} - ${statusText}`
})

// 解析图片URL
const parseImageUrl = (imageUrl) => {
    if (!imageUrl) return ''
    try {
        // 尝试解析为JSON数组
        const urls = JSON.parse(imageUrl)
        if (Array.isArray(urls) && urls.length > 0) {
            const imgUrl = urls[0]
            if (imgUrl.startsWith('http')) return imgUrl
            return `${baseUrl}${imgUrl}`
        }
    } catch (e) {
        // 如果不是JSON格式，继续原有逻辑
        if (imageUrl.startsWith('http')) return imageUrl
        return `${baseUrl}${imageUrl}`
    }
    return ''
}

const getFullLocation = (row) => {
    if (!row) return ''
    // 根据实际返回的数据结构调整
    if (row.area && row.area.includes('省') && row.area.includes('市')) {
        return row.area
    }
    return `${row.province || ''}${row.city || ''}${row.area || ''}`
}

// 获取图片完整URL
const getImageUrl = (url) => {
    return parseImageUrl(url)
}

const fetchData = async () => {
    loading.value = true
    try {
        const response = await axios.get(`${baseUrl}/api/admin/business/list`, {
            params: {
                page: currentPage.value,
                pageSize: pageSize.value,
                apply_status: '0' // 只获取待审核的商家
            }
        })

        if (response.data.code === 200) {
            tableData.value = response.data.data
            total.value = response.data.pagination.total
        } else {
            ElMessage.error(response.data.message || '获取商家列表失败')
        }
    } catch (error) {
        ElMessage.error('获取商家列表失败: ' + error.message)
    } finally {
        loading.value = false
    }
}

const formatDate = (date) => {
    if (!date) return ''
    return date.replace('T', ' ').substring(0, 19)
}

const getStatusText = (status) => {
    const statusMap = { '0': '待审核', '1': '审核通过', '2': '审核失败' }
    return statusMap[status] || '未知状态'
}

const getStatusType = (status) => {
    const typeMap = { '0': 'warning', '1': 'success', '2': 'danger' }
    return typeMap[status] || 'info'
}

const viewDetail = (row) => {
    detailData.value = { ...row }
    // 确保图片URL是完整的
    if (detailData.value.image_url) {
        detailData.value.image_url = parseImageUrl(detailData.value.image_url)
    }
    dialogVisible.value = true
    showRejectReason.value = false
    rejectReason.value = ''
}

// 新增关闭对话框的方法
const closeDialog = () => {
    dialogVisible.value = false
}

const handleDialogClose = (done) => {
    if (showRejectReason.value) {
        ElMessageBox.confirm('确定要关闭页面吗？填写的拒绝原因将会丢失', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }).then(() => {
            // 用户确认关闭
            showRejectReason.value = false
            rejectReason.value = ''
            done()
        }).catch(() => {
            // 用户取消关闭，不执行任何操作
        })
    } else {
        // 直接关闭对话框
        done()
    }
}

const toggleRejectReason = () => {
    showRejectReason.value = true
}

const cancelReject = () => {
    showRejectReason.value = false
    rejectReason.value = ''
}

const approveApplication = async (status) => {
    if (!detailData.value.id) {
        ElMessage.error('无效的商家信息')
        return
    }

    try {
        loading.value = true
        const requestData = {
            apply_status: status
        }

        // 如果是拒绝申请，添加拒绝原因
        if (status === '2') {
            requestData.reject_reason = rejectReason.value
        }

        const response = await axios.put(`${baseUrl}/api/admin/business/${detailData.value.id}`, requestData)

        if (response.data.code === 200) {
            detailData.value.apply_status = status
            const index = tableData.value.findIndex(item => item.id === detailData.value.id)
            if (index !== -1) tableData.value[index].apply_status = status

            if (status === '2') {
                ElMessage.success(`已拒绝【${detailData.value.shop_name}】的申请`)
                rejectReason.value = ''
                showRejectReason.value = false
            } else {
                ElMessage.success(`已通过【${detailData.value.shop_name}】的申请`)
            }

            setTimeout(() => { dialogVisible.value = false }, 1000)
        } else {
            ElMessage.error(response.data.message || '审批操作失败')
        }
    } catch (error) {
        console.error('审批失败:', error)
        ElMessage.error('审批操作失败: ' + error.message)
    } finally {
        loading.value = false
    }
}

const handleSizeChange = (val) => {
    pageSize.value = val
    fetchData()
}

const handleCurrentChange = (val) => {
    currentPage.value = val
    fetchData()
}

onMounted(() => { fetchData() })
</script>

<style scoped>
.merchant-approval-container {
    min-height: calc(100vh - 80px);
}

.header-card {
    background: #409eff;
    color: white;
    padding: 20px 30px;
    border-radius: 8px;
    margin-bottom: 20px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.header-card h2 {
    margin: 0 0 10px 0;
    font-size: 24px;
    font-weight: 500;
}

.header-card p {
    margin: 0;
    opacity: 0.9;
    font-size: 14px;
}

.table-card {
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.pagination-container {
    display: flex;
    justify-content: flex-end;
    margin-top: 20px;
    padding: 15px 0;
}

.detail-dialog :deep(.el-dialog__header) {
    background-color: #f8f9fa;
    border-bottom: 1px solid #ebeef5;
    padding: 15px 20px;
}

.form-value {
    color: #606266;
}

.license-container {
    display: flex;
    align-items: center;
    min-height: 100px;
}

.license-image {
    width: 120px;
    height: 120px;
    border-radius: 6px;
    border: 1px dashed #dcdfe6;
}

.image-slot,
.no-license {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    width: 120px;
    height: 120px;
    color: #c0c4cc;
}

.image-slot i,
.no-license i {
    font-size: 24px;
    margin-bottom: 5px;
}

.no-license {
    border: 1px dashed #dcdfe6;
    border-radius: 6px;
}

.reject-reason {
    margin-top: 20px;
}

.dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
}
</style>